/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

package com.huawei.housekeeper.common.utils;

/**
 * uri转换
 *
 * @author y84241604
 * @since 2022-06-28
 */
public class RegexMatchUtil {
    /**
     * uri转换为正则表达式
     *
     * @param uri
     * @return
     */
    public static String convertURIToRegex(String uri) {
        int lastPointIndex = uri.lastIndexOf('.');
        char[] uriChars = uri.toCharArray();
        StringBuilder regexBuilder = new StringBuilder();
        for (int i = 0, length = uriChars.length; i < length; i++) {
            if (uriChars[i] == '*' && uriChars[i + 1] == '*') {
                regexBuilder.append("(/[^/]*)*");
                i++;
            } else if (uriChars[i] == '*') {
                regexBuilder.append("/[^/]*");
            } else if (uriChars[i] == '.' && i == lastPointIndex) {
                regexBuilder.append("\\.");
                regexBuilder.append(uri.substring(i + 1));
                break;
            } else if (uriChars[i] == '/') {
                if (!uri.substring(i + 1, i + 2).equals("*")) {
                    regexBuilder.append("/");
                }
            } else {
                regexBuilder.append(uriChars[i]);
            }
        }
        return regexBuilder.toString();
    }

}
